package cn.chiship.framework.upms.biz.system.service.impl;

import cn.chiship.framework.upms.biz.system.entity.UpmsRegion;
import cn.chiship.framework.upms.biz.system.entity.UpmsRegionExample;
import cn.chiship.framework.upms.biz.system.mapper.UpmsRegionMapper;
import cn.chiship.framework.upms.biz.system.service.UpmsRegionService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.ProgressResult;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.enums.ProgressResultEnum;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.util.http.HttpUtils;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.sdk.framework.util.ExportUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 地区表业务接口实现层
 * 2021/9/30
 *
 * @author lijian
 */
@Service
public class UpmsRegionServiceImpl extends BaseServiceImpl<UpmsRegion, UpmsRegionExample> implements UpmsRegionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsRegionServiceImpl.class);

    @Resource
    UpmsRegionMapper upmsRegionMapper;

    private String fileName = "行政区划";

    @Override
    @Async
    public void asyncExportData(HttpServletResponse response, String taskId, Map<String, Object> paramMap) {
        try {
            processStatusHm.put(taskId, ProgressResult.out(ProgressResultEnum.PROGRESS_SEARCH_DATABASE_ENUM));
            Thread.sleep(1000);
            ArrayList<String> labels = new ArrayList<>();
            labels.add("区域编码");
            labels.add("区域名称");
            labels.add("级别");
            UpmsRegionExample upmsRegionExample = new UpmsRegionExample();
            upmsRegionExample.setOrderByClause("id asc");
            List<UpmsRegion> regions = upmsRegionMapper.selectByExample(upmsRegionExample);

            List<List<String>> valueList = new ArrayList<>();
            for (UpmsRegion region : regions) {
                List<String> values = new ArrayList<>();
                values.add(region.getAdCode());
                values.add(region.getName());
                values.add(region.getLevel());
                valueList.add(values);
            }
            processStatusHm.put(taskId, ProgressResult.out(ProgressResultEnum.PROGRESS_DOING_ENUM, "查询出" + regions.size() + "条符合条件记录..."));
            Thread.sleep(1000);
            processStatusHm.put(taskId, ProgressResult.out(ProgressResultEnum.PROGRESS_FILE_ASSEMBLY_ENUM));

            /**
             * 此行代码一定要放到最后执行，否则前段永远得不到下载流
             */
            String exportType = paramMap.get("exportType").toString();
            byte[] bytes = ExportUtil.getInstance().getExportBytesByType(exportType, fileName, fileName, labels, valueList);
            processStatusHm.put(taskId, ProgressResult.out(exportType, fileName, bytes));
        } catch (Exception e) {
            e.printStackTrace();
            processStatusHm.put(taskId, ProgressResult.out(ProgressResultEnum.PROGRESS_ERROR_ENUM, e.getLocalizedMessage()));
        }

    }

    @Override
    public BaseResult loadGeoByPidAndName(Long pid, String name) {
        UpmsRegionExample upmsRegionExample = new UpmsRegionExample();
        UpmsRegionExample.Criteria criteria = upmsRegionExample.createCriteria();
        if (-1L == pid) {
            pid = 0L;
        } else {
            criteria.andNameEqualTo(name);
        }
        criteria.andPidEqualTo(pid);
        upmsRegionExample.setOrderByClause("id asc");
        List<UpmsRegion> regions = upmsRegionMapper.selectByExample(upmsRegionExample);
        if (regions.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, null);

        }
        UpmsRegion region = regions.get(0);
        BaseResult baseResult = HttpUtils.doGet("https://cdn-chiship.oss-cn-beijing.aliyuncs.com", "/geo/" + region.getAdCode() + "_full.json");
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        JSONObject json = JSON.parseObject(StringUtil.getString(baseResult.getData()));
        json.put("pid", region.getId());
        return BaseResult.ok(json);
    }
}
